<?php

/**
     * 解密用户敏感数据
     *
     * @param encryptedData 明文,加密数据
     * @param iv            加密算法的初始向量
     * @param code          用户允许登录后，回调内容会带上 code（有效期五分钟），开发者需要将 code 发送到开发者服务器后台，使用code 换取 session_key api，将 code 换成 openid 和 session_key
     * @return
     */
header('Content-type:text/html; Charset=utf8');  
date_default_timezone_set("Asia/Shanghai"); //设置时区   
    
include('./base/conn.php');  	 
include('./base/wxCofig.php');
include_once "./wxphp/vendor/wxBizDataCrypt.php";
$appid      = $appId; //'wx258bc9cbf5ad8eb0';//小程序唯一标识   (在微信小程序管理后台获取)
$appsecret  = $appScreat;//'51988f705c0c8706480f0a2836365035';//小程序的 app secret (在微信小程序管理后台获取)
 echo $appScreat;
$code          = $_POST['code'];
$iv            = $_POST['iv'];
$encryptedData = $_POST['encryptedData'];
$grant_type = "authorization_code"; //授权（必填）
 
$params = "appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
$url = "https://api.weixin.qq.com/sns/jscode2session?".$params;
 
$res = json_decode(httpGet($url),true);
//json_decode不加参数true，转成的就不是array,而是对象。 下面的的取值会报错  Fatal error: Cannot use object of type stdClass as array in
$sessionKey = $res['session_key'];//取出json里对应的值
 
$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data);
 
if ($errCode == 0) {
    $rs=json_decode($data,true);
  
    $openId=$rs['openId'];
    $nickName=$rs['nickName'];
    $gender=$rs['gender'];
    $country=$rs['country'];
    $province=$rs['province'];
    $city=$rs['city'];
    $avatarurl=$rs['avatarUrl'];
    
     $sql="select * from hsxcx_user where openid='".$openId."'  ";
	 $result=mysqli_query($link,$sql);
	 if(mysqli_num_rows($result)<1) {
		
    	 $sql="INSERT INTO hsxcx_user(openid,nickname,avatarurl,gender,country,province,city)
    	 VALUES ('".$openId."','".$nickName."','".$avatarurl."','".$gender."',
    	 '".$country."','".$province."','".$city."')";
		 $result=mysqli_query($link,$sql);
	}else{
  	     $sql="update hsxcx_user set openid='".$openId."',nickname='".$nickName."',
  	     avatarurl='".$avatarurl."',gender='".$gender."',country='".$country."'
  	     ,city='".$city."'   where openid='".$openId."'";
  	      $result=mysqli_query($link,$sql);
  }
           $sqlid="select * from hsxcx_user where openid='".$openId."'  ";
           $result=mysqli_query($link,$sqlid);
           $row = mysqli_fetch_assoc($result);
           $josn=json_encode($row);
           echo $josn;

 
 
 
 
mysqli_close($link);

	
	
  //  print($data . "\n");

} else {
    print($errCode . "\n");
}


function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
  }